import { View, Text, Image } from '@tarojs/components';
import { useDidShow, useRouter, showToast } from '@tarojs/taro';
import { useState, useEffect } from 'react';
import { $route } from '@utils/router';
import calculateScoreAtPosition from './eval';
import black from './gobang/black.png';
import white from './gobang/white.png';
import './gobang.scss';

const Gobang = (props) => {
  // 定义棋盘大小
  const boardSize = 15;

  // 初始化棋盘
  let board = Array(boardSize).fill().map(() => Array(boardSize).fill(0));
  let [gobangBoard, setGobangBoard] = useState(board)
  let [isPlayer, setIsPlayer] = useState(true) // 是否该玩家下棋
  let [isOver, setIsOver] = useState(false) // 是否该玩家下棋

  // 玩家落子
  function handleDownPiece(x,y){
    if(isPlayer && !isOver){
      gobangBoard[x][y] = 2
      setGobangBoard([...gobangBoard])
      setIsPlayer(false)
      let isWin = checkWin(gobangBoard, 2, x, y)
      if(isWin){
        showToast({title: '玩家获胜！', icon: 'none'})
        setIsOver(true)
        return;
      }
      let timer = setTimeout(() => {
        clearTimeout(timer)
        AIPlayer(gobangBoard)
      },1000)
    } else {
      showToast({title: '该AI落子！', icon: 'none'})
    }
  }
  // AI落子
  function AIPlayer(gobangBoard){
    // if(!isPlayer && !isOver){
      // AI 计算最佳落子位置
      let { i, j } = aiMove(gobangBoard)
      console.log('计算位置：', i, j)
      gobangBoard[i][j] = 1
      setGobangBoard([...gobangBoard])
      setIsPlayer(true)
      let isWin = checkWin(gobangBoard, 1, i, j)
      if(isWin){
        showToast({title: 'AI 获胜！', icon: 'none'})
        setIsOver(true)
        return;
      }
    // } else {
    //   showToast({title: '该玩家落子！', icon: 'none'})
    // }
  }
  // 检查指定玩家是否获胜
  function checkWin(board, player, x, y) {
      const directions = [[1, 0], [0, 1], [1, 1], [1, -1]];
      for (let [dx, dy] of directions) {
          let count = 1;
          for (let step = 1; step < 5; step++) {
              if (board[x + step * dx]?.[y + step * dy] === player) {
                  count++;
              } else {
                  break;
              }
          }
          for (let step = 1; step < 5; step++) {
              if (board[x - step * dx]?.[y - step * dy] === player) {
                  count++;
              } else {
                  break;
              }
          }
          if (count >= 5) {
              return true;
          }
      }
      return false;
  }

  // 评估函数，这里非常简单，仅仅基于棋型进行打分
  function evaluate(board) {
      let score = 0;
      for (let i = 0; i < boardSize; i++) {
          for (let j = 0; j < boardSize; j++) {
              if (board[i][j] !== 0) {
                // score += board[i][j] * (checkWin(board, board[i][j], i, j) ? 1000 : 1);
                score = calculateScoreAtPosition(board, i, j, 1)
                console.log('evaluate', score)
              }
          }
      }
      return score;
  }

  // Minimax搜索函数
  function minimax(board, depth, isMaximizingPlayer, alpha, beta) {
      if (depth === 0 || checkWin(board, 1, 0, 0) || checkWin(board, -1, 0, 0)) {
          return evaluate(board);
      }

      if (isMaximizingPlayer) {
          let bestScore = -Infinity;
          for (let i = 0; i < boardSize; i++) {
              for (let j = 0; j < boardSize; j++) {
                  if (board[i][j] === 0) {
                      board[i][j] = 1;
                      let score = minimax(board, depth - 1, false, alpha, beta);
                      board[i][j] = 0;
                      bestScore = Math.max(bestScore, score);
                      alpha = Math.max(alpha, score);
                      if (beta <= alpha) {
                          break;
                      }
                  }
              }
          }
          return bestScore;
      } else {
          let bestScore = Infinity;
          for (let i = 0; i < boardSize; i++) {
              for (let j = 0; j < boardSize; j++) {
                  if (board[i][j] === 0) {
                      board[i][j] = -1;
                      let score = minimax(board, depth - 1, true, alpha, beta);
                      board[i][j] = 0;
                      bestScore = Math.min(bestScore, score);
                      beta = Math.min(beta, score);
                      if (beta <= alpha) {
                          break;
                      }
                  }
              }
          }
          return bestScore;
      }
  }

  // AI下棋
  function aiMove(board) {
    let bestMove = null;
    let bestScore = -Infinity;
    // 看看棋盘中是否落子
    let isDownPieces = board.reduce((prev,acc) => [...prev,...acc],[]).filter(val => val !== 0)
    if(isDownPieces.length == 0){
      return {
        i: Math.round(boardSize/ 2),
        j: Math.round(boardSize / 2)
      }
    }
    for (let i = 0; i < boardSize; i++) {
      for (let j = 0; j < boardSize; j++) {
        if (board[i][j] === 0) {
          board[i][j] = 1;
          let score = minimax(board, 1, false, -Infinity, Infinity);
          board[i][j] = 0;
          if (score > bestScore) {
            bestScore = score;
            bestMove = { i, j };
          }
        }
      }
    }
    return bestMove;
  }

  // 示例用法
  // console.log(aiMove()); // 输出最佳落子位置
  // console.log(evaluateScore(board, 1))
  // 获取棋子图片
  function getPieceImage(val){
    if(val == 1){
      return <Image src={black} className="rui-piece-li"></Image>
    } else if(val == 2){
      return <Image src={white} className="rui-piece-li"></Image>
    }
  }
  return <View className='rui-gobang-page-board-content'>
    {
      gobangBoard.map((item,i) => <View 
        key={`row-${i}`} 
        id={`row-${i}`} 
        className='rui-row-li'>
        {
          item.map((cur,j) => <View 
            key={`${i}-cell-${j}`} 
            id={`${i}-cell-${j}`} 
            onClick={handleDownPiece.bind(null,i,j)}
            className='rui-cell-li'>
              { getPieceImage(cur) }
            </View>)
        }
      </View>)
    }
    
  </View>
}
export default Gobang;